home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 31 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  69 lines

  1. Path: ix.netcom.com!netnews
  2. From: dannyyoo@ix.netcom.com (Danny Yoo)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help!
  5. Date: Mon, 01 Jan 1996 04:51:58 GMT
  6. Organization: Netcom
  7. Message-ID: <30e76088.1216430@nntp.ix.netcom.com>
  8. References: <4c2me5$ke6@news-e2a.gnn.com>
  9. NNTP-Posting-Host: ix-scr-ca1-13.ix.netcom.com
  10. X-NETCOM-Date: Sun Dec 31  9:00:02 PM PST 1995
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. Gary Hagen <GaryJ@gnn.com> wrote:
  14. >I am currently learning the C++ language.I need help with a 
  15. >programming exercise.Here is the code.
  16.  
  17.  
  18. >Whatever number I enter for the carnum array of 
  19. >structures,all it gives me is the last car and year that I 
  20. >entered as many times as the entered carnum.I guess my 
  21. >problem is that I'm not accessing each structure in the 
  22.     The problem I saw was that you're not doing anything with the
  23. increments.  You have a pointer, ps, but it doesn't access the rest of
  24. your allocated space.  You can access them by either incrementing the
  25. pointer itself:
  26.     ps++;
  27. or you could just do what I did and just use pointer arithmetic.
  28.  
  29.     I modified the program (hopefully it should work).  I've made
  30. a few modifications, some of them probably unwanted <grin>, but you
  31. can fix the rest of my convolted code.  Here is the completed program:
  32.  
  33. #include <iostream.h>
  34. struct car {
  35.     char make[31];
  36.     // since you limited the size of the name string, I set this
  37.     // to 31
  38.     int year;
  39. };
  40.  
  41. void main(void) {
  42.     const int MAX=100;  // MAX is the maximum cars you want
  43.  
  44.     int temp, carnum;
  45.     do {
  46.         cout << "Please enter the number of cars to catalog:";
  47.         cin >> carnum;
  48.     }
  49.     while(carnum < 1 || carnum > MAX);  // I changed this part
  50.     // from the ambiguous 'continue' that you used.  I'm not
  51.     // exactly sure if this is what you meant or not, but this
  52.     //should  limit the range from 1 to 100.
  53.  
  54.     car * ps = new car[carnum];  // allocates enough space
  55.  
  56.     for(temp=0; temp < carnum; temp++) {
  57.         cout << "\nEnter make of car: ";
  58.         cin >> (ps+temp)->make;
  59.         cout << "Enter model year: ";
  60.         cin >> (ps+temp)->year;
  61.         cout << "\n\n";
  62.     }
  63. // I use tem as my increment variable.  (ps+0) is the first element,
  64. // (ps+1) the first, (ps+3) the third, etc...
  65.     for(temp = 0;temp<carnum;temp++)
  66.         cout << (ps+temp)->year << " " << (ps+temp)->make
  67.                 << "\n";
  68. }
  69.